package com.lyl.security.common.sercurity.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lyl.security.common.exception.BizException;
import com.lyl.security.common.sercurity.model.pojo.LoginUser;
import com.lyl.security.model.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Mr.Luo
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static List<User> userList;

    @PostConstruct
    void init() {
        userList = ListUtil.toList(
                User.builder().id(1).username("张三").password("$2a$10$qOOo3fAqmiHKmXqG/kE6pOAkvI9X9HULjH6nas/GFphsilLVI0ChG").build(),
                User.builder().id(2).username("李四").password("$2a$10$qOOo3fAqmiHKmXqG/kE6pOAkvI9X9HULjH6nas/GFphsilLVI0ChG").build(),
                User.builder().id(3).username("王五").password("$2a$10$qOOo3fAqmiHKmXqG/kE6pOAkvI9X9HULjH6nas/GFphsilLVI0ChG").build()
        );
    }

    private User findByUsername(String username) {
        return userList.stream().filter(user -> ObjectUtil.equals(username, user.getUsername()))
                .findFirst().orElseThrow(() -> new BizException("找不到用户"));
        //.findFirst().orElseGet(User::new);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("{} 进行登录认证操作", username);
        User user = findByUsername(username);
        return new LoginUser(user);
    }
}
